package com.ititer.mail;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.ititer.mail.MailTemplate.TemplateType;

public class MailSender {
	private String userName;
	private String password;
	private String stmpServer;
	private String senderEmailAddr;
	private MailTemplate templates;
	private boolean inited = false;
	private JavaMailSenderImpl sender = null;

	private void init() {
		sender = new JavaMailSenderImpl();
		sender.setHost(stmpServer);
		sender.setUsername(userName);
		sender.setPassword(password);
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", stmpServer);
		sender.setJavaMailProperties(props);
		inited = true;
	}

	public void sendRegisterMail(String email, String password, String activeUrl) {
		String body = templates.getBody(TemplateType.Register);
		String content = String.format(body, email, email, password, activeUrl, activeUrl);

		String subject = templates.getSubject(TemplateType.Register);
		sendMail(email, subject, content);
	}

	public void sendMail(String to, String subject, String concept) {
		if (!inited) {
			init();
		}

		MimeMessage msg = sender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			helper = new MimeMessageHelper(msg, true, "UTF-8");
			helper.setFrom(senderEmailAddr);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(concept, true);
			sender.send(msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setSenderEmailAddr(String senderEmailAddr) {
		this.senderEmailAddr = senderEmailAddr;
	}

	public void setStmpServer(String stmpServer) {
		this.stmpServer = stmpServer;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setTemplates(MailTemplate templates) {
		this.templates = templates;
	}
}